<script setup>
import { ref, onMounted, watch } from 'vue'
import Chart from 'chart.js/auto'

const props = defineProps({
  labels: Array,
  data: Array,
  label: String,
  color: String
})

const chartRef = ref(null)
let chartInstance = null

onMounted(() => {
  renderChart()
})

watch(() => [props.labels, props.data], () => {
  if (chartInstance) {
    chartInstance.destroy()
  }
  renderChart()
})

function renderChart() {
  const ctx = chartRef.value.getContext('2d')
  
  chartInstance = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: props.labels,
      datasets: [{
        label: props.label,
        data: props.data,
        backgroundColor: props.color + '80',
        borderColor: props.color,
        borderWidth: 2,
        borderRadius: 6,
        hoverBackgroundColor: props.color
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        },
        tooltip: {
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          padding: 12,
          cornerRadius: 8,
          displayColors: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        x: {
          grid: {
            display: false
          }
        }
      }
    }
  })
}
</script>

<template>
  <canvas ref="chartRef" height="250"></canvas>
</template>